from django.shortcuts import render
from django.views import View
from django.conf import settings
from django.http import JsonResponse, HttpResponse
from libs.captcha.captcha import captcha
from ronglian_sms_sdk import SmsSDK
from django_redis import get_redis_connection
from apps.user.models import User
import logging
import random
from celery_tasks.sms.tasks import sms_send
logger = logging.getLogger('django')
# Create your views here.






class SmsCodeView(View):
    def get(self, request, mobile):
        '''短信验证码'''
        # 获取参数
        redis_conn = get_redis_connection('code')
        pl = redis_conn.pipeline()
        image_code_clent = request.GET.get('image_code')
        uuid_clent = request.GET.get('image_code_id')
        sms_count = redis_conn.get(mobile)

        # 效验参数
        if not all([image_code_clent, uuid_clent]):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数缺失'})
        if sms_count != None:
            return JsonResponse({'code': 400,
                                 'errmsg': '手机号频凡发短信'})
        mobile_count = User.objects.filter(modile=mobile).count()
        if mobile_count != 0:
            return JsonResponse({'code': 400,
                                 'errmsg': '手机号重复'})


        image_code_server = redis_conn.get('img_%s' % uuid_clent)
        if image_code_server == None:

            return JsonResponse({'code': 400,
                                 'errmsg': '验证码过期'})
        image_code_server = image_code_server.decode()
        if image_code_server.lower() != image_code_clent.lower():
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码错误'})
        # 生成，保存手机验证码
        sms = '%05d' % random.randint(0, 99999)
        sms_data = (sms,)
        try:
            pl.setex('sms_%s' % mobile, 60, sms)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码无法保存'})
        logger.info(sms)
        # sm = SmsSDK(settings.ACCID, settings.ACCTOKEN, settings.APPID)
        # 发送手机验证码使用celery异步
        try:
            # sm.sendMessage('1', mobile, sms_data)
            sms_send.delay(mobile, sms_data)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '发送失败'})
        # 标记手机号
        pl.setex(mobile, 200, 1)

        #提交redis
        pl.execute()
        return JsonResponse({'code': 0,
                            'errmsg': 'ok'})

# ===============================================================================================================

# 图片验证码
class ImageCodeView(View):
    def get(self, request, uuid):
        '''图片验证码'''
        # 生成验证码
        text, image = captcha.generate_captcha()
        if not all([text, image]):
            logger.error('验证码生成失败')
        logger.info(text)
        # 保存验证码
        redis_conn = get_redis_connection('code')
        try:
            redis_conn.setex('img_%s' % uuid, 60, text)
        except Exception as e:
            logger.error(e)



        # 返回验证码
        return HttpResponse(image, content_type='image/jpeg')



